<template>
    <view class="add-form-container">
        <!-- 页面头部组件 -->
        <page-header :title="id ? '编辑任务' : '新增任务'"></page-header>

        <!-- 使用地块选择器组件 -->
        <LandSelector
            ref="landSelector"
            :multiple="true"
            @selection-change="handleLandSelectionChange"
        ></LandSelector>

        <!-- 使用条田选择器组件 -->
        <SectionSelector
            ref="sectionSelector"
            @areaChange="handleAreaChange"
            @usersChange="handleUsersChange"
        ></SectionSelector>

        <view class="basic-info">
            <view class="section-title">基础信息</view>

            <uni-forms
                ref="form"
                :modelValue="formData"
                :rules="rules"
                validateTrigger="bind"
                label-position="top"
                class="farm-form"
            >
                <uni-forms-item label="日期" name="dateRange" required>
                    <uni-datetime-picker
                        type="daterange"
                        v-model="formData.dateRange"
                        :border="false"
                        @change="dateRangeChange"
                    >
                        <view class="uni-date-picker-container">
                            <text :class="{ placeholder: !formData.dateRangeText }">
                                {{ formData.dateRangeText || "请选择日期" }}
                            </text>
                            <view class="date-icon">
                                <roc-icon-plus type="fas" name="calendar-alt" :size="18" color="#999"></roc-icon-plus>
                            </view>
                        </view>
                    </uni-datetime-picker>
                </uni-forms-item>

                <uni-forms-item label="负责人" name="personInCharge" required>
                    <uni-easyinput
                        v-model="formData.personInCharge"
                        placeholder="请输入负责人姓名"
                        disabled
                    ></uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="土地面积" name="area" required>
                    <uni-easyinput
                        type="digit"
                        v-model="formData.area"
                        placeholder="请输入"
                        disabled
                    >
                        <template #right>
                            <text class="input-unit">亩</text>
                        </template>
                    </uni-easyinput>
                </uni-forms-item>

            

                <uni-forms-item label="工作事项" name="workTypes" required>
                    <view class="work-type-selector">
                        <view 
                            class="work-type-item" 
                            v-for="(type, index) in workTypes" 
                            :key="index"
                            :class="{ active: formData.workTypes === type.value }"
                            @click="selectWorkType(type.value)"
                        >
                            <image 
                                :src="formData.workTypes === type.value ? type.activeIcon : type.defaultIcon" 
                                mode="aspectFit" 
                                class="work-icon" 
                            />
                            <text class="work-label">{{ type.label }}</text>
                        </view>
                    </view>
                </uni-forms-item>

                <uni-forms-item label="工作内容" name="workContent" required>
                    <uni-easyinput
                        type="textarea"
                        v-model="formData.workContent"
                        placeholder="请输入工作内容"
                        :maxlength="200"
                    ></uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="备注" name="remark">
                    <uni-easyinput
                        type="textarea"
                        v-model="formData.remark"
                        placeholder="请输入备注信息"
                        :maxlength="200"
                    ></uni-easyinput>
                </uni-forms-item>
            </uni-forms>
        </view>

        <view class="photo-section">
            <view class="section-title">现场照片</view>
            <image-uploader
                ref="imageUploader"
                :images="formData.images"
                :maxCount="9"
            />
        </view>

        <view class="submit-btn-container">
            <view class="submit-btn" @click="submitForm">点击上传</view>
        </view>
    </view>
</template>

<script>
import PageHeader from "@/components/PageHeader/index.vue";
import LandSelector from "@/components/LandSelector/index.vue";
import SectionSelector from "@/components/SectionSelector/index.vue";
import ImageUploader from "@/components/ImageUploader/index.vue";
import { createFarmingSchedule, updateFarmingSchedule, getFarmingSchedule } from "@/utils/api/myTask.js";
import { getWorkTypeOptions, getWorkTypeLabels } from "@/utils/dict.js";
import { mapGetters, mapActions } from "vuex";
import { formatDate, getDefaultDateRange } from '@/utils/util.js'

export default {
    components: {
        PageHeader,
        LandSelector,
        SectionSelector,
        ImageUploader,
    },
    data() {
        const defaultDateRange = getDefaultDateRange()
        return {
            id: null,
            formData: {
                dateRange: defaultDateRange.dateRange,
                dateRangeText: defaultDateRange.dateRangeText,
                area: "",
                personInId: "",
                personInCharge: "",
                workTypes: "", // 改为字符串类型
                workContent: "",
                remark: "",
                images: [],
                plotId: "", // 地块ID
                fieldId: "", // 条田ID
            },
            rules: {
                dateRange: {
                    rules: [{ required: true, errorMessage: "请选择日期" }],
                },
                area: {
                    rules: [
                        { required: true, errorMessage: "请输入土地面积" },
                        { format: "number", errorMessage: "请输入有效的数字" },
                    ],
                },
                personInCharge: {
                    rules: [{ required: true, errorMessage: "请输入负责人" }],
                },
                workTypes: {
                    rules: [{ required: true, errorMessage: "请选择工作事项" }],
                },
                workContent: {
                    rules: [{ required: true, errorMessage: "请输入工作内容" }],
                },
            },
            selectedLands: [],
            selectedSections: [],
            workTypes: getWorkTypeOptions(), // 直接使用工作事项字典函数
        };
    },
    computed: {
        ...mapGetters({
            getDictByType: "getDictByType",
            getDictLabel: "getDictLabel",
            userInfo: "getUserInfo", // 添加用户信息
        }),
    },
    onLoad(options) {
        if (options.id) {
            this.id = options.id;
            this.loadTaskDetail(this.id);
        } else {
            // 设置默认的负责人和负责人ID
            console.log('用户信息', this.userInfo)
            this.formData.personInId = this.userInfo.id
            this.formData.personInCharge = this.userInfo.nickname
        }
        this.loadDictData();
        console.log('枚举1：')
        console.log(this.workTypes)
    },
    methods: {
        ...mapActions(["getDictByType"]),

        async loadDictData() {
            try {
                uni.showLoading({ title: "加载字典数据..." });
                // 不再需要从后端加载工作事项字典
                uni.hideLoading();
            } catch (error) {
                console.error("加载字典数据失败:", error);
                uni.hideLoading();
                uni.showToast({
                    title: "加载字典数据失败",
                    icon: "none",
                });
            }
        },

        async loadTaskDetail(id) {
            try {
                uni.showLoading({ title: "加载中..." });
                const res = await getFarmingSchedule(id);

                if (res.code === 0 && res.data) {
                    const taskData = res.data;

                    // 设置日期范围
                    let startDate = new Date(taskData.startDate);
                    let endDate = taskData.endDate ? new Date(taskData.endDate) : startDate;

                    this.formData = {
                        dateRange: [
                            startDate.toISOString().split("T")[0],
                            endDate.toISOString().split("T")[0],
                        ],
                        dateRangeText: `${formatDate(startDate)} 至 ${formatDate(endDate)}`,
                        area: taskData.area ? taskData.area.toString() : "",
                        personInId: taskData.personInId || "",
                        personInCharge: taskData.personInCharge || "",
                        workTypes: taskData.workTask || "", // 直接赋值
                        workContent: taskData.remarks || "",
                        remark: taskData.remark || "",
                        images: this.formatImages(taskData.images),
                        plotId: taskData.plotId || "",
                        fieldId: taskData.fieldId || "",
                    };

                    // 设置地块和条田选择状态
                    this.$nextTick(() => {
                        setTimeout(() => {
                            if (this.$refs.landSelector && this.formData.plotId) {
                                this.$refs.landSelector.setSelectedLands(this.formData.plotId);
                                this.updateSelectedLands();

                                if (this.$refs.sectionSelector && this.formData.fieldId) {
                                    this.$refs.sectionSelector.setSelectedParcels(this.selectedLands);
                                    this.$refs.sectionSelector.setSelectedFields(this.formData.fieldId);
                                    this.updateSelectedSections();
                                }
                            }
                        }, 1200);
                    });
                }
                uni.hideLoading();
            } catch (error) {
                console.error("加载数据失败:", error);
                uni.hideLoading();
                uni.showToast({
                    title: "加载数据失败",
                    icon: "none",
                });
            }
        },

        formatImages(images) {
            if (!images) return [];
            if (typeof images === "string") {
                return images.includes(",") ? images.split(",") : [images];
            }
            return Array.isArray(images) ? images : [];
        },

        dateRangeChange(e) {
            if (e && e.length === 2) {
                const startDate = new Date(e[0]);
                const endDate = new Date(e[1]);
                this.formData.dateRangeText = `${formatDate(startDate)} 至 ${formatDate(endDate)}`;
            } else {
                this.formData.dateRangeText = "";
            }
        },

        handleLandSelectionChange() {
            this.updateSelectedLands();
        },

        handleAreaChange(area) {
            this.formData.area = area;
        },
        handleUsersChange(users){
            console.log('负责人变了')
            console.log(users)
            this.formData.personInId = users.map(item => item.userId).join(',')
            this.formData.personInCharge = users.map(item => item.userName).join(',')
        },

        updateSelectedLands() {
            if (this.$refs.landSelector) {
                this.selectedLands = this.$refs.landSelector.getSelectedLands();
                if (this.$refs.sectionSelector) {
                    this.$refs.sectionSelector.setSelectedParcels(this.selectedLands);
                    this.updateSelectedSections();
                }
            }
        },

        updateSelectedSections() {
            if (this.$refs.sectionSelector) {
                this.selectedSections = this.$refs.sectionSelector.getSelectedSections();
            }
        },

        selectWorkType(type) {
            this.formData.workTypes = type;
        },

        validateForm() {
            this.updateSelectedLands();
            this.updateSelectedSections();

            if (!this.$refs.landSelector.validate()) {
                uni.showToast({
                    title: "请选择至少一个地块",
                    icon: "none",
                });
                return false;
            }

            if (!this.$refs.sectionSelector.validate()) {
                uni.showToast({
                    title: "请选择至少一个条田",
                    icon: "none",
                });
                return false;
            }

            return true;
        },

        submitForm() {
            this.$refs.form.validate().then((result) => {
                if (this.validateForm()) {
                    this.submitFormData();
                }
            }).catch((errors) => {
                console.log("表单错误信息：", errors);
            });
        },

        async submitFormData() {
            try {
                this.updateSelectedLands();
                this.updateSelectedSections();

                let plotId = this.selectedLands.map(item => item.id);
                let fieldId = this.selectedSections.map(item => item.id);
                let plotName = this.selectedLands.map(item => item.name);
                let fieldName = this.selectedSections.map(item => item.name);

                const imageList = this.$refs.imageUploader.getImageList();
                // 新增任务：负责人id  personInId  负责人  personInCharge ，逗号隔开
                const submitData = {
                    id: this.id,
                    startDate: this.formData.dateRange[0],
                    endDate: this.formData.dateRange[1],
                    plotId: plotId?.join(","),
                    fieldId: fieldId?.join(","),
                    plotName: plotName?.join(","),
                    fieldName: fieldName?.join(","),
                    area: parseFloat(this.formData.area),
                    personInId: this.formData.personInId,
                    personInCharge: this.formData.personInCharge,
                    workTask: this.formData.workTypes, // 直接使用单个值
                    remarks: this.formData.workContent,
                    images: imageList.join(","),
                    remark: this.formData.remark || "",
                    status: "0" // 默认未完成状态
                };

                uni.showLoading({ title: "提交中..." });

                let res;
                if (this.id) {
                    res = await updateFarmingSchedule(submitData);
                } else {
                    res = await createFarmingSchedule(submitData);
                }

                uni.hideLoading();

                if (res.code === 0) {
                    uni.showToast({
                        title: this.id ? "修改成功" : "添加成功",
                        icon: "success",
                        duration: 2000,
                        success: () => {
                            setTimeout(() => {
                                uni.navigateBack({ delta: 1 });
                            }, 1500);
                        },
                    });
                } else {
                    uni.showToast({
                        title: res.msg || "操作失败",
                        icon: "none",
                        duration: 2000,
                    });
                }
            } catch (error) {
                uni.hideLoading();
                console.error("提交数据失败:", error);
                uni.showToast({
                    title: "提交失败，请重试",
                    icon: "none",
                    duration: 2000,
                });
            }
        },
    },
};
</script>

<style lang="scss">


.work-type-selector {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(20%, 1fr));
    gap: 20rpx;

    .work-type-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20rpx;
        border-radius: 8rpx;
        &.active {
            .work-label {
                color: #2e6140;
            }
        }
        
        .work-icon {
            width: 92rpx;
            height: 92rpx;
            margin-bottom: 10rpx;
        }

        .work-label {
            font-size: 24rpx;
            color: #333;
            text-align: center;
        }
    }
}

</style> 